# coding=utf-8
# author:xc
# datetime:2018/9/28 11:39

from . import api
from dbConnection.MysqlConn import Mysql
from flask import request
from app import upload_files, util


#  首页数据
@api.route('/api/user/home', methods=['POST', 'GET'])
def api_user_home():
    try:
        mysql = Mysql()
        recommend_sql = "select b.cid,b.courseName,b.cover,b.addTime,b.info from girl_recommend " \
                        "as a left join girl_course as b on a.cid=b.cid where b.status=1 "
        recommend_res = mysql.getAll(recommend_sql, None)
        category_sql = "select sid,typeName,info,addTime from girl_subject where status=1 limit 0, 4"
        category_res = mysql.getAll(category_sql, None)
        public_sql = "select b.cid,b.courseName,b.cover,b.addTime,b.info from girl_public " \
                     "as a left join girl_course as b on a.cid=b.cid where b.status=1 order by addTime desc limit 0,3"
        public_res = mysql.getAll(public_sql, None)
        supreme_sql = "select b.cid,b.courseName,b.cover,b.addTime,b.info from girl_supreme " \
                      "as a left join girl_course as b on a.cid=b.cid where b.status=1 order by addTime desc limit 0,4 "
        supreme_res = mysql.getAll(supreme_sql, None)
        recommend = []
        category = []
        res = {}
        result = {}
        code = util.CODE_SUCCESS
        if recommend_res:
            for x in recommend_res:
                data = dict()
                data['cid'] = x['cid']
                data['courseName'] = x['courseName']
                if not x['cover'].startswith('http'):
                    data['cover'] = upload_files.baseUrl + x['cover']
                else:
                    data['cover'] = x['cover']
                data['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data['info'] = x['info']
                recommend.append(data)
        if category_res:
            category = category_res
        if public_res:
            res['flag'] = 1
            res['name'] = u"公开课"
            public = []
            for x in public_res:
                data = dict()
                data['cid'] = x['cid']
                data['courseName'] = x['courseName']
                if not x['cover'].startswith('http'):
                    data['cover'] = upload_files.baseUrl + x['cover']
                else:
                    data['cover'] = x['cover']
                data['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data['info'] = x['info']
                public.append(data)
            res['data'] = public
        if supreme_res:
            result['flag'] = 2
            result['name'] = u"精品课"
            supreme = []
            for x in supreme_res:
                data = dict()
                data['cid'] = x['cid']
                data['courseName'] = x['courseName']
                if not x['cover'].startswith('http'):
                    data['cover'] = upload_files.baseUrl + x['cover']
                else:
                    data['cover'] = x['cover']
                data['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data['info'] = x['info']
                supreme.append(data)
            result['data'] = supreme
        mysql.dispose()
    except Exception as e:
        print e
        result = {}
        res = {}
        category = []
        recommend = []
        code = util.CODE_ERROR
    data = {
        'recommend': recommend,
        'category': category,
        'public': res,
        'supreme': result,
        'code': code
    }
    return util.to_json(data)


# 最近更新
@api.route('/api/user/recent', methods=['POST', 'GET'])
def api_user_recent():
    try:
        mysql = Mysql()
        sql = "select * from girl_course order by addTime desc limit 0,6"
        result = mysql.getAll(sql, None)
        mysql.dispose()
        list_detail = []
        code = util.CODE_EMPTY
        if result:
            code = util.CODE_SUCCESS
            for k in result:
                data_detail = dict()
                data_detail['cid'] = k['cid']
                data_detail['courseName'] = k['courseName']
                data_detail['flag'] = k['flag']
                if not k['cover'].startswith('http'):
                    data_detail['cover'] = upload_files.baseUrl + k['cover']
                else:
                    data_detail['cover'] = k['cover']
                data_detail['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data_detail['info'] = k['info']
                list_detail.append(data_detail)
    except Exception as e:
        print e
        code = util.CODE_ERROR
        list_detail = []
    data = {
        'res': list_detail,
        'code': code
    }
    return util.to_json(data)


# 获取心灵成长
@api.route('/api/user/category', methods=['POST', 'GET'])
def api_girl_spiritual():
    try:
        sid = request.values.get('sid')
        mysql = Mysql()

        sql = "select a.tid ,a.courseName,a.info from girl_type as a where a.status=1 and sid ='%s'" % sid
        result = mysql.getAll(sql, None)
        code = util.CODE_EMPTY
        data = []
        if result:
            code = util.CODE_SUCCESS
            for x in range(0, len(result)):
                data_title = dict()
                data_title['name'] = result[x]['courseName']
                data_title['tid'] = result[x]['tid']
                if result[x]['info'] is None:
                    data_title['info'] = ""
                else:
                    data_title['info'] = result[x]['info']
                data.append(data_title)
        mysql.dispose()
    except Exception as e:
        print e
        data = []
        code = util.CODE_ERROR
    data = {
        'code': code,
        'data': data,
    }
    return util.to_json(data)


# 分类列表
@api.route('/api/type/list', methods=['POST', 'GET'])
def api_type_list():
    try:
        tid = request.values.get('tid')
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        sql2 = " select b.* from  girl_course as b where b.status=1 and b.tid='%s' order by b.addTime desc limit %d,%d " % (
            tid, num, util.PAGE_NUM)
        mysql = Mysql()
        detail = mysql.getAll(sql2, None)
        mysql.dispose()
        list_detail = []
        code = util.CODE_EMPTY
        if detail:
            code = util.CODE_SUCCESS
            for k in detail:
                data_detail = dict()
                data_detail['cid'] = k['cid']
                data_detail['courseName'] = k['courseName']
                data_detail['flag'] = k['flag']
                if not k['cover'].startswith('http'):
                    data_detail['cover'] = upload_files.baseUrl + k['cover']
                else:
                    data_detail['cover'] = k['cover']
                data_detail['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                data_detail['info'] = k['info']
                list_detail.append(data_detail)
    except Exception as e:
        print e
        list_detail=[]
        code = util.CODE_ERROR
    data = {
        'res': list_detail,
        'code': code
    }
    return util.to_json(data)
